package cn.monkey.state.core;

import java.util.function.Supplier;

public abstract class AbstractBatchUpdateStateGroup extends AbstractStateGroup {
    public AbstractBatchUpdateStateGroup(String id, StateContext stateContext, Supplier<Long> timer) {
        super(id, stateContext, timer);
    }


    @Override
    public void update() {
        if (null == this.currentState) {
            return;
        }
        try {
            this.currentState.init(this.timer);
        } catch (Throwable e) {
            this.currentState.onInitError(this.timer, e);
            return;
        }
        boolean currentStateChanged;
        boolean canAutoUpdate = this.currentState.canAutoUpdate();
        boolean updated = false;
        Object poll;
        while ((poll = this.eventQueue.poll()) != null) {
            updated = true;
            try {
                this.currentState.fireEvent(this.timer, poll);
            } catch (Throwable e) {
                this.currentState.onFireEventError(this.timer, poll, e);
                break;
            }
            currentStateChanged = this.updateAndTrySwitch2NextState();
            if (currentStateChanged) {
                if (this.currentState == null) {
                    break;
                }
                try {
                    this.currentState.init(this.timer);
                } catch (Throwable e) {
                    this.currentState.onInitError(this.timer, e);
                    break;
                }
                canAutoUpdate = this.currentState.canAutoUpdate();
            }
        }

        if (!updated && canAutoUpdate) {
            this.updateAndTrySwitch2NextState();
        }
    }
}
